import { observable, action } from 'mobx';
import { WeaForm, WeaTableNew } from 'comsMobx';

const { TableStore } = WeaTableNew;

import * as RECEIVE_DOC_APIS from '../apis/receiveDoc';
import * as COLLECTION_RECEIVE_APIS from '../apis/collectionReceive';
import * as COLLECTIONSEND_APIS from '../apis/collectionSend';
import * as SEND_DOC_APIS from '../apis/sendDoc';

export default class CommonStore {
  constructor() {
    // 用于获取高级搜索的表单控件的数据的异步后台接口，根据页面和tab的切换会变
    this.interfaceOfGetCondition = null;

    this.interfaceOfDeleteTableData = null;

    this.interfaceOfGetBaseinfo = null;

    this.interfaceOfGetTreeData = null;
  }

  @observable loading = false;

  @observable ifShowSearchAd = false;

  @observable tableStore = new TableStore();

  // 用于控制传给weatable的sessionkey
  @observable dataKey = '0';

  // 切换tab页时用来标识当前位于哪个tab的变量
  @observable viewcondition = '0';

  /* 高级搜素相关store */
  @observable adSearchForm = new WeaForm();
  @observable conditioninfo = '';

  @observable topTab = [];
  @observable pagetitle = '';
  @observable CHANGE_MODE = 'WS';
  /** 左侧树store */
  @observable leftTree = [];
  @observable leftTreeCount = {};
  @observable leftTreeCountType = [];
  @observable selectedTreeKey = '';
  @observable hasRight = true;

  @action
  setStoreAttr = (attr, val) => {
    this[attr] = val;
  };

  @action
  getTreeData() {
    this.interfaceOfGetTreeData().then((data) => {
      this.leftTree = data.treedata;
      this.leftTreeCount = data.treecount;
      this.leftTreeCountType = data.countcfg;
      // this.leftTreeCount = data.treecount;
    });
  }

  // compStore: weaformstore定义为哪个store的observable
  @action
  reinitWeaForm = (compStore, weaformStoreName, condition) => {
    compStore[weaformStoreName] = new WeaForm();
    compStore[weaformStoreName].initFormFields(condition);
  };

  // 根据不同的页面动态的设置不同页面所需要的后台接口
  setInterfaces = () => {
    if (this.pageName === 'receiveDoc') {
      this.interfaceOfGetCondition = RECEIVE_DOC_APIS.getCondition.bind(this);
      this.interfaceOfDeleteTableData = RECEIVE_DOC_APIS.getList.bind(this);
      this.interfaceOfGetBaseinfo = RECEIVE_DOC_APIS.getBaseinfo;
    } else if (this.pageName === 'collectionReceive') {
      this.interfaceOfGetCondition = COLLECTION_RECEIVE_APIS.getCondition.bind(
        this,
      );
      this.interfaceOfDeleteTableData = COLLECTION_RECEIVE_APIS.getList.bind(
        this,
      );
      this.interfaceOfGetBaseinfo = COLLECTION_RECEIVE_APIS.getBaseinfo;
      this.interfaceOfGetTreeData = COLLECTION_RECEIVE_APIS.getTreeNode;
    } else if (this.pageName === 'sendDoc') {
      this.interfaceOfGetCondition = SEND_DOC_APIS.getCondition.bind(this);
      this.interfaceOfDeleteTableData = SEND_DOC_APIS.getList.bind(this);
      this.interfaceOfGetBaseinfo = SEND_DOC_APIS.getBaseinfo;
    } else if (this.pageName === 'collectionSend') {
      const officalTypeValIndex =
        window.location.href.indexOf('officalType') + 12;
      const officalType = window.location.href.substring(
        officalTypeValIndex,
        officalTypeValIndex + 1,
      );
      this.interfaceOfGetCondition = COLLECTIONSEND_APIS.getCondition.bind(
        this,
        officalType,
      );
      this.interfaceOfDeleteTableData = COLLECTIONSEND_APIS.getList.bind(
        this,
        officalType,
      );
      this.interfaceOfGetBaseinfo = COLLECTIONSEND_APIS.getBaseinfo.bind(
        this,
        officalType,
      );
      this.interfaceOfGetTreeData = COLLECTIONSEND_APIS.getTreeNode.bind(
        this,
        officalType,
      );
    }
    //  else if(this.pageName === 'WorkPlanSearch'){
    //     this.interfaceOfGetCondition = SEARCHAPI.getCondition.bind(this);
    //     this.interfaceOfDeleteTableData = SEARCHAPI.getlist.bind(this);
    //
    // }
  };

  // 做的事情：1.切换tab的同时切换并初始化高级搜索的表单域 2.根据tab的切换显示不同的表格数据
  // params得是一个对象，结构为：
  // {
  // interfaceParams:表示用来传给后端异步接口用来获取后台数据的一个参数对象
  // CompParams:表示与当前组件相关的一些特殊参数的对象
  //     其中的viewcondition表示store.viewcondition即将变成这个viewcondition
  //     viewconditiondomkey是可选的，如weatab的切换也伴随着高级搜素中某字段的变化，那么高级搜索相关字段的
  //          domkey要当做值传入viewconditiondomkey，若weatab的切换不会伴随着高级搜素中某字段的变化，则此字段无需传入
  // }
  @action
  initData = (
    params = {
      compParams: {
        // 必传，代表切换tab后的vc，若组件调用此方法时没传入vc，则默认为当前的vc值而不变
        viewcondition: this.viewcondition,
        // viewconditiondomkey:可选的参数，详见dosearch解释传还是不传
      },
    },
  ) => {
    // 在加载数据前先切换tab，防止切换tab的卡顿
    this.viewcondition = params.compParams.viewcondition;

    // 在初始化数据开始前应该有进度条表示数据正在加载
    this.setStoreAttr('loading', true);

    this.setInterfaces(params.compParams.viewcondition);

    this.interfaceOfGetBaseinfo({ menuType: params.compParams.menuType, isInnerChange: params.compParams.isInnerChange }).then(
      action('getBaseinfoSucc', (data) => {
        this.pagetitle = data.pagetitle;
        this.topTab = data.groupinfo;
        this.CHANGE_MODE = data.CHANGE_MODE;
      }),
    )
      .then(
        action('setBaseinfoSucc', () => {
          // 这里面是用来初始化高级搜素里的表单的
          this.interfaceOfGetCondition({ menuType: params.compParams.menuType, isInnerChange: params.compParams.isInnerChange }).then(
            action('getConditionSucc', (data) => {
              const { condition } = data;
              this.conditioninfo = condition;
              this.adSearchForm.initFormFields(this.conditioninfo);

              if (this.pageName === 'collectionSend' || this.pageName === 'collectionReceive') {
                this.doSearch({
                  ifAdFormCgWhenCgTab: false,
                  behavior: 'changeTab',
                  // viewconditiondomkey: params.compParams.viewconditiondomkey,
                  viewcondition: params.compParams.viewcondition,
                  otherInterfaceParams: {
                    viewcondition: params.compParams.viewcondition,
                  },
                });
                this.getTreeData();
              } else if (this.pageName === 'receiveDoc' || this.pageName === 'sendDoc') {
                this.doSearch({
                  ifAdFormCgWhenCgTab: true,
                  behavior: 'changeTab',
                  viewconditiondomkey: params.compParams.viewconditiondomkey,
                  viewcondition: params.compParams.viewcondition,
                  otherInterfaceParams: {
                    menuType: params.compParams.menuType,
                    isInnerChange: params.compParams.isInnerChange,
                    state: params.compParams.state,
                  },
                });
              } else {
                this.doSearch({
                  ifAdFormCgWhenCgTab: true,
                  behavior: 'changeTab',
                  viewconditiondomkey: params.compParams.viewconditiondomkey,
                  viewcondition: params.compParams.viewcondition,
                });
              }
            }),
          );
        }),
      );
  };

  // dosearch中做的是
  // 根据动态的接口获取并筛选要显示的表格数据，并在成功显示筛选后的数据后调用可选的回调
  //
  //
  // 具体代码思路：
  //     behavior:'search'时
  //         此刻dosearch要做的即:
  //             1.ifAdFormCgWhenCgTab为true时，(此刻要传vckey)，不用传vc，此刻要做的效果就是点搜索的同时切换tab，所以要根据adsearchparams改变store中的vc，然后getList
  //             2.ifAdFormCgWhenCgTab为false时，此刻不要传vckey，不用传vc，此刻要做的效果就是单纯的筛选数据，直接getlist
  //
  //
  //     behavior:'changeTab'时
  //         此刻dosearch要做的即:
  //             1.ifAdFormCgWhenCgTab为true时，此刻要传vckey，要传vc，此刻要做的效果就是切换tab的同时更新adsearchform中某字段(即vckey)的值，所以要根据传进来的vc重置AdForm并更新AdForm的vckey的值，然后getlist
  //             2.ifAdFormCgWhenCgTab为false时，此刻不要传vckey，要传vc，值应该为vc，key名动态变化，此刻要做的效果就是reset AdForm，然后getlist

  //     behavior:'changeLefTreeMenu'时
  //         此刻dosearch要做的即:
  //             1.ifAdFormCgWhenCgLefTreeMenu为true时，此刻要传menuDomkey，要传menuValObj(即用做adForm中相应menuDomkey的属性值)，此刻要做的效果就是切换leftmenu的同时更新adsearchform中某字段(即menuDomkey)的值，所以要根据传进来的menuValObj重置AdForm并更新AdForm的menuDomkey的值，然后getlist

  //      还有两种情况也要做判断
  //      1.ifAdFormCgWhenCgTab为true、behavior:'search'时，在高级搜索中字段选择完成时点搜索时weatab也随之变化的情况下，
  //      要提前检查高级搜索中viewconditiondomkey的值是否是所有weatab的selectedkeys中的其中一个，若是，则
  //      高级搜索中viewconditiondomkey值是什么，weatab的selectedkey就会变成什么，若不是，则weatab的selectedkey会变成0
  //
  //
  //      2.ifAdFormCgWhenCgTab为true、behavior:'changeTab'时，即在切换tab时中高级搜索中某字段(且这个字段为的type为DateGroup时)随之变化的情况下，
  //      因为设置DateGroup的默认值不同于其他表单域，得传进三个domkey才能设置，所以此刻得多传入一个值，为linkedFormType：DateGroup，且vckey得传入xxx__xxx__xxx形式
  // params得是一个对象，结构为：
  // {
  // behavior: 必填，值只能是'changeTab'表示切换tab页 or 'search'表示点了搜索按钮的行为
  // ifAdFormCgWhenCgTab: 选填，true or false，表示切换tab时高级搜索中是否也有值随之变化
  // ifAdFormCgWhenCgLefTreeMenu: 选填，true or false，表示切换leftmenu时高级搜索中是否也有值随之变化
  // viewcondition,表示将要切换到的tab的key值
  // viewconditiondomkey，高级搜索中的那个同事也用于表示weatab的selectedkey的domkey，如高级搜素中某字段的变化也伴随着weatab的切换，那么高级搜索这个字段的domkey要当做值传入viewconditiondomkey
  // linkedFormType：DateGroup：仅在上面代码思路中的最后一种情况下需要传入，且值为’DateGroup‘
  //
  //
  // //除了传递高级搜索的参数，其他一些参数可能也要传进来，放到otherInterfaceParams中
  // otherInterfaceParams:一个对象，指除了wea-form的参数还要传给后端的其他参数
  // }
  @action
  doSearch = (params = {}, cb) => {
    // 在搜索开始前应该有进度条表示数据正在加载
    this.setStoreAttr('loading', true);

    const { behavior, ifAdFormCgWhenCgTab } = params;
    const adSearchFormParams = this.adSearchForm.getFormParams();

    if (behavior === 'search') {
      if (ifAdFormCgWhenCgTab === true) {
        const { viewconditiondomkey } = params;
        //      还有一种情况也要做判断，ifAdFormCgWhenCgTab为true时，即高级搜索中字段选择完成时点搜索时weatab也随之变化的情况下，
        //      要提前检查高级搜索中viewconditiondomkey的值是否是所有weatab的selectedkeys中的其中一个，若是，则
        //      高级搜索中viewconditiondomkey值是什么，weatab的selectedkey就会变成什么，若不是，则weatab的selectedkey会变成0
        if (
          this.topTab.some(
            elem =>
              elem.viewcondition == adSearchFormParams[viewconditiondomkey],
          )
        ) {
          this.viewcondition = adSearchFormParams[viewconditiondomkey];
        } else {
          // this.viewcondition = 0;
        }
      }
    } else if (behavior === 'changeTab') {
      // 首先vc都是要变的
      const { viewcondition } = params;
      this.viewcondition = viewcondition;

      if (ifAdFormCgWhenCgTab === true) {
        const { viewconditiondomkey } = params;
        this.viewcondition = viewcondition;

        if (params.linkedFormType === 'DateGroup') {
          this.adSearchForm.updateFields({
            [viewconditiondomkey]: {
              value: [viewcondition],
            },
          });
        } else {
          this.adSearchForm.updateFields({
            [viewconditiondomkey]: {
              value: viewcondition,
            },
          });
        }
      }
    } else if (behavior === 'changeLefTreeMenu') {
      const { ifAdFormCgWhenCgLefTreeMenu } = params;
      if (ifAdFormCgWhenCgLefTreeMenu === true) {
        const { menuDomkey, menuValObj } = params;
        this.adSearchForm.updateFields({
          [menuDomkey]: menuValObj,
        });
      }
    }
    this.tableStore = new TableStore();
    // 除了传递高级搜索的参数，其他一些参数可能也要传进来，放到otherInterfaceParams中
    this.interfaceOfDeleteTableData({
      ...this.adSearchForm.getFormParams(),
      ...params.otherInterfaceParams,
    }).then(
      action('fetchDataSuccess', (data) => {
        this.hasRight = data.hasRight != false;
        if (data.sessionkey) {
          this.tableStore.getDatas(data.sessionkey, 1);
        }
        this.dataKey = data.sessionkey;

        this.setStoreAttr('loading', false); // 加载完数据清除进度条

        cb && cb(this.viewcondition);
      }),
    );
  };
}
